# 
# (C)2008 Ctyle System, Inc. All Rights Reserved.
# 
# Ruby Application / NetBeans IDE 6.1 / Mac X OS
# 
# Author: tony cheung
# 2008/08/08 at Beijng

#
# Pay Attention:
# CSS fils and its images are the intellectual property. 
# 

#How to use?
#First para :a site domain,look like www.ctyle.com
#Second para:a site port  ,default 80 or other numbers
#Third para :a file path  ,file path,look like "/beijing/helloworld.css"
#PS:This application can only be used to download css's images.

#如何使用此脚本
#第一个参数:网站域名,例如: www.ctyle.com ,无http://
#第二个参数:网站端口,一般默认80,
#第三个参数:文件在网站的目录地址,例如/beijing/helloworld.css
#注意:这个程序只用于下载CSS文件中的图片,并按原路径归类.

require 'pathname'
require 'net/http' 
require "fileutils"

puts "Starting ..."

#
#　完成下载功能
#
def down(domain,path)
  dpath =  File.dirname(__FILE__)
  Dir.chdir(dpath)
  dir = File.dirname(path)     
  filename = File.basename(path)   
  puts dir
  puts filename
  
  lp = "#{dpath}/#{domain}/#{dir}"
  if !FileTest.exist?("#{dpath}/#{domain}/#{dir}")
    FileUtils.makedirs("#{dpath}/#{domain}/#{dir}")
  end
  
  Dir.chdir(lp) 
 
  downloadpath ="/"+ path
  Net::HTTP.start(domain) { |http|
  resp = http.get(downloadpath)
 
  open( filename, "wb") { |file|
    file.write(resp.body)
   }
  
}
puts "Down..." + domain +"/"+ path +"/"+filename
end
#
# 设置参数
#

if $*[0] == nil
  $*[0] = "localhost"
end

if $*[1] == nil
  $*[1] = 80
end

if $*[2] == nil
  $*[2] = "/briefing/styles/b.css"
end

#
#　主程序
#

puts "Connecting..."+$*[0]
h = Net::HTTP.new($*[0],$*[1])
resp,data = h.get($*[2],nil)
if resp.message == "OK" 
  puts "Loading..."
  urlcollection=[]
  urlcollection = data.scan(/http:\/\/(.*?)\/(\S+)\)/)
  puts urlcollection.length
  urlcollection.each {|i|
  down(i[0],i[1])
  }
end
puts "Your Task is finished. Have a nice day."
